﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ProjectManageSystemApi.Models;
using ProjectManageSystemApi.Models.CostApply;
using ProjectManageSystemApi.Services;
using ProjectManageSystemApi.Utilities;

namespace ProjectManageSystemApi.Controllers
{
    /// <summary>
    /// 费用申请Api
    /// </summary>
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = Grouping.GroupName_v1)]
    public class CostApplyController : ControllerBase
    {
        readonly ILogger<AuthController> _logger;
        readonly ICostApplyService _costApplyService;
        readonly IUserServices _userServices;
        public CostApplyController(ILogger<AuthController> logger, ICostApplyService costApplyService, IUserServices user)
        {
            _logger = logger;
            _costApplyService = costApplyService;
            _userServices = user;
        }

        /// <summary>
        /// 财务获取报销信息
        /// </summary>
        [HttpPost, Route("GetAllByFinancer")]
        public ApiResult GetAllByFinancer([FromBody] PageBo<CostApplyParams> pageBo)
        {
            if (pageBo == null || pageBo.Param == null || pageBo.Param.ProjectId == 0 || pageBo.Param.ItemId == 0)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            var data = _costApplyService.GetAllByFinancer(pageBo);
            return ApiResultStatus.Success(data);
        }

        /// <summary>
        /// 项目经理获取报销信息
        /// </summary>
        [HttpPost, Route("GetAllByManager")]
        public ApiResult GetAllByManager([FromBody] PageBo<CostApplyParams> pageBo)
        {
            if (pageBo == null || pageBo.Param == null || pageBo.Param.ProjectId == 0 || pageBo.Param.ItemId == 0)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            var data = _costApplyService.GetAllByManager(pageBo);
            return ApiResultStatus.Success(data);
        }

        /// <summary>
        /// 获取报销信息
        /// </summary>
        [HttpPost, Route("GetAll")]
        public ApiResult GetAll([FromBody] PageBo<CostApplyParams> pageBo)
        {
            if (pageBo == null || pageBo.Param == null || pageBo.Param.ProjectId == 0 || pageBo.Param.ItemId == 0)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            var data = _costApplyService.GetAll(pageBo);
            return ApiResultStatus.Success(data);
        }


        /// <summary>
        /// 创建报销
        /// </summary>
        [HttpPost, Route("Create")]
        public ApiResult Create([FromHeader(Name = "Authorization")] string auth, [FromBody]CostApplyDto costInfo)
        {
            if (costInfo == null || costInfo.ProjectId == 0 || costInfo.CostTypeId == 0 
                || string.IsNullOrWhiteSpace(costInfo.CostName)) 
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }

            if (!_userServices.GetUserIdByToken(auth.ReplaceBearer(), out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            costInfo.UserId = userId;
            costInfo.CreateUserId = userId;
            costInfo.Id = 0;
            if (!_costApplyService.Create(costInfo))
            {
                return ApiResultStatus.Fail(ApiResultCodes.OPERATION_FAILED);
            }
            return ApiResultStatus.Success();
        }

        /// <summary>
        /// 修改报销
        /// </summary>
        [HttpPost, Route("Update")]
        public ApiResult Update([FromHeader(Name = "Authorization")] string auth, [FromBody] CostApplyDto costInfo)
        {
            if (costInfo == null || costInfo.ProjectId == 0 || costInfo.CostTypeId == 0
                || costInfo.Id == 0 || string.IsNullOrWhiteSpace(costInfo.CostName))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }

            if (!_userServices.GetUserIdByToken(auth.ReplaceBearer(), out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            costInfo.UserId = userId;
            if (!_costApplyService.HasExistById(costInfo.Id))
            {
                return ApiResultStatus.Fail(ApiResultCodes.DATA_NOT_EXIST);
            }
            if (!_costApplyService.HasAllowUpdate(costInfo.Id))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PROJECT_COST_DEAL_WITH);
            }
            if (!_costApplyService.Update(costInfo))
            {
                return ApiResultStatus.Fail(ApiResultCodes.OPERATION_FAILED);
            }
            return ApiResultStatus.Success();
        }

        /// <summary>
        /// 财务审核
        /// </summary>
        [HttpPost,Route("FinancerAudit")]
        public ApiResult FinancerAudit([FromHeader(Name = "Authorization")] string auth, [FromBody] CostCheckData data)
        {
            if (data == null || data.Id <= 0)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (!_userServices.GetUserIdByToken(auth.ReplaceBearer(), out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }

            if (!_costApplyService.HasExistById(data.Id))
            {
                return ApiResultStatus.Fail(ApiResultCodes.DATA_EXIST);
            }
            if (!_costApplyService.HasStatus(data.Id, EnumCostApplyInfo.ManagerPassed))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PROJECT_COST_DEAL_WITH);
            }
            if (!_costApplyService.FinancerCostCheck(data, userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.OPERATION_FAILED);
            }
            return ApiResultStatus.Success();
        }

        /// <summary>
        /// 经理审核
        /// </summary>
        [HttpPost, Route("ManagerAudit")]
        public ApiResult ManagerAudit([FromHeader(Name = "Authorization")] string auth, [FromBody] CostCheckData data)
        {
            if (data == null || data.Id <= 0)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (!_userServices.GetUserIdByToken(auth.ReplaceBearer(), out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (!_costApplyService.HasExistById(data.Id))
            {
                return ApiResultStatus.Fail(ApiResultCodes.DATA_EXIST);
            }
            if (!_costApplyService.HasStatus(data.Id, EnumCostApplyInfo.Nomal))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PROJECT_COST_DEAL_WITH);
            }
            if (!_costApplyService.ManagerCostCheck(data, userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.OPERATION_FAILED);
            }
            return ApiResultStatus.Success();
        }

        /// <summary>
        /// 修改报销状态， 1：同意，2：拒绝，3：删除
        /// </summary>
        [HttpPost, Route("UpdateState")]
        public ApiResult UpdateState([FromBody] CostInfoStateBo costInfoState)
        {
            if (costInfoState == null || costInfoState.CostId <= 0)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (!_costApplyService.HasExistById(costInfoState.CostId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.DATA_EXIST);
            }
            if (!_costApplyService.HasAllowUpdate(costInfoState.CostId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PROJECT_COST_DEAL_WITH);
            }
            EnumCostApplyInfo state;
            switch (costInfoState.State)
            {
                case 1:
                    state = EnumCostApplyInfo.ManagerPassed;
                    break;
                case 2:
                    state = EnumCostApplyInfo.ManagerUnPassed;
                    break;
                case 3:
                    state = EnumCostApplyInfo.Delete;
                    break;
                default:
                    return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (!_costApplyService.UpdateState(costInfoState.CostId, state))
            {
                return ApiResultStatus.Fail(ApiResultCodes.OPERATION_FAILED);
            }
            return ApiResultStatus.Success();
        }

        /// <summary>
        /// 客户端调用, 获取我的申请列表
        /// </summary>
        /// <param name="pageBo"></param>
        /// <returns></returns>
        [HttpPost, Route("GetMyCostApplyList")]
        public ApiResult GetMyCostApplyList([FromHeader(Name = "Authorization")] string auth, [FromBody]PageBo<GetMyCostApplyListBo> pageBo)
        {
            if (pageBo == null)
            {
                pageBo = new PageBo<GetMyCostApplyListBo>();
            }
            if (pageBo.Param == null) 
            {
                pageBo.Param = new GetMyCostApplyListBo();
            }

            if (!_userServices.GetUserIdByToken(auth.ReplaceBearer(), out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            pageBo.Param.UserId = userId;

            var data = _costApplyService.GetMyCostApplyList(pageBo);
            return ApiResultStatus.Success(data);
        }
        
        /// <summary>
        /// 客户端调用，获取详细
        /// </summary>
        [HttpGet,Route("GetCostApplyById")]
        public ApiResult GetCostApplyById(int id) 
        {
            if (id == 0) 
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            var data = _costApplyService.GetCostInfoById(id);
            return ApiResultStatus.Create(data != null, ApiResultCodes.DATA_NOT_EXIST, data);
        }
        
    }
}
